package com.gem.controller;

import com.gem.domain.User;
import com.gem.service.UserService;
import com.gem.util.Md5Util;
import com.gem.util.MessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @Author: 玲
 * @Description:
 * @create 2019-10-28 21:14
 * @Modified By:
 */
@Controller
public class UserController {

    @Autowired
    private UserService service;

    @RequestMapping("/member/login")
    @ResponseBody
    public String login(HttpSession session, User user) {
        try {
            User loginUser = service.login(user);
            if (loginUser != null) {
                loginUser.setPassword("");
                session.setAttribute("user", loginUser);
                return "1";
            } else {
                return "0";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "-1";
        }
    }

    @RequestMapping("/member/updatePasswordUI")
    public String updatePasswordUI() {
        return "member/updatePassword";
    }

    @RequestMapping("/member/updatePassword")
    public String updatePassword(HttpSession session, Integer uid, Model model,
                                 @RequestParam(value = "newPassword") String newPassword) {
        try {
            String password = Md5Util.encodeByMd5(newPassword);
            service.updatePassword(password,uid);
            MessageUtil.returnInfoPage("3", "/member/loginOut", "密码修改成功！", model);
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/starter", "服务器异常！请联系管理员！", model);
        }
        return "message";
    }


    @RequestMapping("/member/loginOut")
    public String loginOut(HttpSession session) {
        session.invalidate();
        return "member/login";
    }
}
